package quan.dong.handle;

import android.os.Handler;
import android.os.Message;
import quan.dong.common.Common;
import quan.dong.common.CommonEnums;
import quan.dong.common.Constant;
import quan.dong.common.TCPSocket;
import quan.dong.object.PriceAlert;

public class CreateAlert implements Runnable {
	PriceAlert priceAlert = new PriceAlert();
	String imeiNumber;
	Thread runner;
	TCPSocket socket;
	Handler handler;

	public CreateAlert(PriceAlert priceAlert, String imeiNumber,
			Handler handler, String threadName) {
		super();
		this.priceAlert = priceAlert;
		this.imeiNumber = imeiNumber;
		this.handler = handler;
		runner = new Thread(this, threadName);
	}

	public void Start() {
		runner.start();
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		TCPSocket socket = new TCPSocket();
		try {
			boolean isConnected = socket.Create(Constant.SERVER_IP_ADDRESS,
					Constant.PORT);
			if (isConnected) {
				socket.SendExact(Common
						.intToByteArray(CommonEnums.ConnectType.CreateAlert
								.ordinal()));
				// send imeiNumber
				byte[] buffer = imeiNumber.getBytes();
				int len = buffer.length;
				socket.SendExact(Common.intToByteArray(len));
				socket.SendExact(buffer);

				socket.SendExact(priceAlert.Serialize());
				buffer = new byte[4];
				socket.ReadExact(buffer);
				Message message = handler.obtainMessage(
						Constant.HANDLER_CREATE_ALERT,
						Common.byteArrayToInt(buffer));
				handler.sendMessage(message);
			} else {
				Message message = handler.obtainMessage(
						Constant.HANDLER_CREATE_ALERT,
						CommonEnums.RetCode.SystemError.ordinal());
				handler.sendMessage(message);
			}
		} catch (Exception e) {

		}
	}

}
